package com.oig.sys.base.controller;

import com.oig.common.constants.CommonEnum;
import com.oig.common.module.SysPageInfo;
import com.oig.common.module.SysRequest;
import com.oig.common.module.SysResponse;
import com.oig.common.validator.GroupAdd;
import com.oig.common.validator.GroupEdit;
import com.oig.sys.base.app.IAppHsGoodsService;
import com.oig.sys.base.dto.HsGoodsDto;
import com.oig.sys.base.vo.HsGoodsVo;
import com.oig.sys.log.annotation.SysLog;
import com.oig.sys.security.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "海关商品管理hsCode维护")
@RestController
@RequestMapping("/hsGoods")
@Slf4j
@RequiredArgsConstructor
public class TbHsGoodsController {

    private final IAppHsGoodsService appHsGoodsService;


    @PreAuthorize("@pms.hasPermission('/hsGoods/add')")
    @SysLog(value="添加海关商品",apiUrl="/hsGoods/add")
    @Operation(summary = "添加海关商品")
    @PostMapping("/add")
    public HsGoodsVo add(@RequestBody @Validated(value = GroupAdd.class) HsGoodsDto hsGoodsDto){
        log.info("add hsGoods:{}",hsGoodsDto);
        if (hsGoodsDto.getOrgzId()==null){
            hsGoodsDto.setOrgzId(SecurityUtil.getDefineUserMain().getTenantId());
            hsGoodsDto.setOrgzName(SecurityUtil.getDefineUserMain().getTenantName());
        } else {
            log.info("add HsGoods for son");
            SecurityUtil.getDefineUserMain().checkTenantPermission(hsGoodsDto.getOrgzId());
        }
        return this.appHsGoodsService.addHsGoods(hsGoodsDto);
    }

    @PreAuthorize("@pms.hasPermission('/hsGoods/update')")
    @SysLog(value="修改海关商品",apiUrl="/hsGoods/update")
    @Operation(summary = "修改海关商品")
    @PostMapping("/update")
    public HsGoodsVo update(@RequestBody @Validated(GroupEdit.class) HsGoodsDto hsGoodsDto){
        log.info("update hsGoods :{}", hsGoodsDto);
        if (hsGoodsDto.getOrgzId()==null){
            hsGoodsDto.setOrgzId(SecurityUtil.getDefineUserMain().getTenantId());
            hsGoodsDto.setOrgzName(SecurityUtil.getDefineUserMain().getTenantName());
        } else {
            log.info("add HsGoods for son");
            SecurityUtil.getDefineUserMain().checkTenantPermission(hsGoodsDto.getOrgzId());
        }
        return this.appHsGoodsService.updateHsGoods(hsGoodsDto);
    }

    @PreAuthorize("@pms.hasPermission('/hsGoods/cancel')")
    @SysLog(value="注销海关商品",apiUrl="/hsGoods/cancel")
    @Operation(summary = "注销海关商品")
    @PostMapping("/cancel/{hsCode}")
    public SysResponse<String> cancel(@PathVariable("hsCode") String hsCode){
        log.info("cancel hsGoods:{}", hsCode);
        this.appHsGoodsService.cancelHsGoods(hsCode);
        return SysResponse.ok(hsCode);
    }

    @Operation(summary = "获取海关商品详细信息")
    @PostMapping("/info/{hsCode}")
    public HsGoodsVo info(@PathVariable("hsCode") String hsCode){
        log.info("get hsGoods info:{}", hsCode);
        return this.appHsGoodsService.getHsGoods(hsCode);
    }

    @Operation(summary = "查询海关商品", description = "批文筛选需要")
    @PostMapping(value = "/findList")
    public SysPageInfo<HsGoodsVo> findList(@RequestBody SysRequest<HsGoodsDto> hsGoodsDtoSysRequest){
        log.info("find hsGoods :{}", hsGoodsDtoSysRequest);
        return this.appHsGoodsService.listHsGoods(hsGoodsDtoSysRequest);
    }


    @Operation(summary = "抓取海关商品信息及税率--后面去掉，只有主表的部分信息")
    //@SysLog(value="抓取海关商品及税率",apiUrl="/hsGoods/startSpiderAll")
    @PostMapping(value = "/startSpiderAll")
    public SysResponse<String> startSpiderAll(){
        log.info("start spider...");
        SysRequest<HsGoodsDto> hsGoodsSysRequest = new SysRequest<>();
        hsGoodsSysRequest.setPageNo(1);
        hsGoodsSysRequest.setPageSize(100);
        HsGoodsDto hsGoodsDto = new HsGoodsDto();
        hsGoodsDto.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
        hsGoodsSysRequest.setParamDto(hsGoodsDto);
        this.loopSpider(hsGoodsSysRequest);
        return SysResponse.ok("开始抓取海关商品信息及税率");
    }


    private void loopSpider(SysRequest<HsGoodsDto> hsGoodsSysRequest){
        log.debug("hsGoodsSysRequest:{}", hsGoodsSysRequest);
        SysPageInfo<HsGoodsVo> hsGoodsPage =  this.appHsGoodsService.listHsGoods(hsGoodsSysRequest);
        List<String> hsCodeList = hsGoodsPage.getList().stream().map(HsGoodsVo::getHsCode).collect(Collectors.toList());
        log.debug("hsCodeList:{}", hsCodeList);
        this.appHsGoodsService.startSpider(hsCodeList);
        if (hsGoodsPage.isHasNextPage()){
            hsGoodsSysRequest.setPageNo(hsGoodsPage.getNextPage());
            this.loopSpider(hsGoodsSysRequest);
        }
    }


    @Operation(summary = "海关官网抓取税率")
    //@SysLog(value="海关官网抓取税率",apiUrl="/hsGoods/startSpiderAllFromGov")
    @PostMapping(value = "/startSpiderAllFromGov")
    public SysResponse<String> startSpiderAllFromGov(){
        log.info("start spider all from gov...");
        SysRequest<HsGoodsDto> hsGoodsSysRequest = new SysRequest<>();
        hsGoodsSysRequest.setPageNo(1);
        hsGoodsSysRequest.setPageSize(200);
        HsGoodsDto hsGoodsDto = new HsGoodsDto();
        hsGoodsDto.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
        hsGoodsSysRequest.setParamDto(hsGoodsDto);
        this.loopSpiderAllFromGov(hsGoodsSysRequest);
        return SysResponse.ok("开始抓取海关商品信息及税率");
    }

    private void loopSpiderAllFromGov(SysRequest<HsGoodsDto> hsGoodsSysRequest){
        log.debug("loopSpiderAllFromGov:{}", hsGoodsSysRequest);
        SysPageInfo<HsGoodsVo> hsGoodsPage =  this.appHsGoodsService.listHsGoods(hsGoodsSysRequest);
        for (HsGoodsVo hsGoodsVo : hsGoodsPage.getList()){
            if(hsGoodsVo.getHsCode().length()>=10){
                try {
                    this.appHsGoodsService.startSpider(hsGoodsVo.getHsCode());
                }catch (Exception e){
                    log.info("海关官网抓取税率失败，hscode:{}", hsGoodsVo.getHsCode());
                }
            }
        }
        if (hsGoodsPage.isHasNextPage()){
            hsGoodsSysRequest.setPageNo(hsGoodsPage.getNextPage());
            this.loopSpiderAllFromGov(hsGoodsSysRequest);
        }
    }

    @Operation(summary = "单个抓取海关商品信息及税率-海关官网")
    @SysLog(value="单个抓取海关商品及税率-海关官网",apiUrl="/hsGoods/startSpider")
    @PostMapping(value = "/startSpider/{hsCode}")
    public SysResponse<String> startSpider(@PathVariable(name="hsCode") String hsCode){
        log.info("start spider...{}", hsCode);
        appHsGoodsService.startSpider(hsCode);
        return SysResponse.ok(hsCode,"开始抓取海关商品信息及税率");
    }

    @Operation(summary = "获取海关商品名称")
    @PostMapping("/getName")
    public String getName(@RequestParam("hsCode") String hsCode){
        log.info("get name by hsCode:{}", hsCode);
        return this.appHsGoodsService.getName(hsCode);
    }

    @Operation(summary = "获取海关商品详细信息")
    @PostMapping("/getInfoByHsCode")
    public HsGoodsVo getInfoByHsCode(@RequestParam("hsCode") String hsCode){
        log.info("get hsGoods info:{}", hsCode);
        return this.appHsGoodsService.getHsGoods(hsCode);
    }

    @Operation(summary = "批量获取海关商品详细信息")
    @PostMapping("/listInfoByHsCode")
    public List<HsGoodsVo> listInfoByHsCode(@RequestBody List<String> hsCodeList){
        log.info("list hsGoods info:{}", hsCodeList);
        return this.appHsGoodsService.listInfoByHsCode(hsCodeList);
    }
}
